﻿using System;
using System.Collections.Specialized;
using System.Text;
using System.Text.RegularExpressions;
using App_Code.Helpers;
using Rss;

namespace App_Code.SiteParsers
{
    /// <summary>
    /// Summary description for VipmovieNetParser
    /// </summary>
    public class VipmovieNetParser : BasePluginParser
    {
        private enum SearchMode
        {
            s,  //Series
            m   //Movies
        }

        protected const string DEFAULT_URL = "http://vipmovie.net";
        private const string SEARCH_URL = "http://vipmovie.net/?act=search&terms={0}&t={1}";
        private const SearchMode _searchMode = SearchMode.m;

        private readonly Encoding _pageEcoding = Encoding.GetEncoding("windows-1255");

        public VipmovieNetParser()
        {
            this._defaultUrl = DEFAULT_URL;

            this.Name = "VipMovie.Net";
            this.Description = "ברוכים הבאים לאתר הצפייה הישירה בסרטים ובסדרות VipMovie VipMovie הינו אתר חדש אך מתקדם במהירות גדולה! אתם מוזמנים לצפות במגוון הסרטים והסדרות שקיימים באתר ולהנות,אנו נדאג כדי שלכם יהיה את הטוב ביותר...";
            this.Url = DEFAULT_URL;            
        }

        #region Implementation of IPluginParser
        public override RssFeed Run(NameValueCollection queryStringParams)
        {
            this.InitMembers(queryStringParams);

            switch (this._pluginMode)
            {
                case PluginMode.IDLE_MODE:
                        return LoadMovies();

                case PluginMode.NEXT_PAGE_MODE:
                        return LoadMovies();

                case PluginMode.MOVIE_MODE:
                        return this.LoadMovie();
                
                case PluginMode.SEARCH_MODE:
                        this.Url = string.Format(SEARCH_URL, this.SearchText, _searchMode);
                        return this.LoadMovies();
            }

            return null;
        }

        public override void RunUntillPage(int pageNumber)
        {
            for (var i = 1; i <= pageNumber; i++)
            {
                this.Url = string.Format("{0}/p{1}#start_movies_list", DEFAULT_URL, i);                
                this.LoadMovies();                
            }
        }
        #endregion

        #region Private Methods
        private RssFeed LoadMovies()
        {
            try
            {
                var feed = LoadFromCache(this.Url);
                if (feed != null) return feed;

                var page = Utils.GetPage(this.Url, this._pageEcoding);

                var rssChannel = new RssChannel
                {
                    Title = "Movies Channel",
                    Description = "Movies List",
                    Link = new Uri(string.Format("{0}?pluginId={1}", Utils.GetSiteUrl(), this._pluginId)),
                    Language = "he"
                };

                rssChannel.LastBuildDate = rssChannel.Items.LatestPubDate();

                this.AddSearchLink(rssChannel, SEARCH_URL);

                const string moviesContainerExpression = "<div class=\"MOVIESimg\"><img src=\"(.+?)\" class=\"img\" alt=\"(.+?)\".+?<div class=\"MOVIEStxt_title\"><a.*?href=\"(.+?)\"><b>(.+?)</b></a>.+?<div class=\"MOVIEStxt_info\">(.*?)</div>";
                var exp = new Regex(moviesContainerExpression, RegexOptions.Singleline);
                var matches = exp.Matches(page);
                foreach (Match match in matches)
                {
                    var movieImage = match.Groups[1].Value;
                    var movieTitle = match.Groups[2].Value;
                    var moviePageLink = DEFAULT_URL + match.Groups[3].Value;

                    var movie = new Movie
                                    {
                                        Name = movieTitle,
                                        ImageLink = movieImage,
                                    };

                    var pageContent = Utils.GetPage(moviePageLink, this._pageEcoding);
                    movie.Plot = GetPlot(pageContent, movieTitle);
                    movie.MovieLinks = GetMovieLinks(pageContent);

                    if (movie.MovieLinks.Count > 0)
                    {
                        var movieItems = movie.GetRssItems(Utils.GetSiteUrl(), this._pluginId,
                                                           (int) PluginMode.MOVIE_MODE);
                        foreach (var movieItem in movieItems)
                        {
                            rssChannel.Items.Add(movieItem);
                        }
                    }
                }

                var nextPageMovie = new Movie
                {
                    Name = "דף הבא",
                };

                nextPageMovie.MovieLinks.Add(GetNextPageLink(page));
                var nextPageItems = nextPageMovie.GetRssItems(Utils.GetSiteUrl(), this._pluginId, (int)PluginMode.NEXT_PAGE_MODE);
                rssChannel.Items.Add(nextPageItems[0]);

                feed = new RssFeed { Encoding = System.Text.Encoding.UTF8 };
                feed.Channels.Add(rssChannel);

                this.AddToCache(this.Url, feed);

                return feed;
            }
            catch (Exception ex)
            {
                return CreateErrorResponse(ex.Message);
            }
        }

        private string GetNextPageLink(string pageContent)
        {
            try
            {
                const string moviePlotExpression = "class=\"MOVIESpaging\">.*?class=\"current\">.*?<a href=\"(.+?)\"";
                var exp = new Regex(moviePlotExpression, RegexOptions.Singleline);
                var match = exp.Match(pageContent);
                if (match.Success)
                {
                    return string.Format("{0}/{1}", DEFAULT_URL, match.Groups[1].Value.Trim());
                }
            }
            catch { }

            return string.Format("{0}/p{1}#start_movies_list", DEFAULT_URL, 1);
        }

        private string GetPlot(string pageContent, string movieTitle)
        {
            try
            {
                var moviePlotExpression = "class=\"SWITCH_BOXbg\">.*?<b>" + movieTitle + "</b> <span>|</span>.*?</b><br />(.+?)<br><br>.*?<center>";
                var exp = new Regex(moviePlotExpression, RegexOptions.Singleline);
                var match = exp.Match(pageContent);
                if (match.Success)
                {
                    return match.Groups[1].Value.Trim();
                }
            }
            catch{}

            return string.Empty;
        }
        #endregion
    }
}